<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018-04-27
 * Time: 16:44
 */

/*
 *将推荐信息存入表中
 * @param $type 推荐类型：文章（咨询）news、圈子quan、话题topic、用户member、商家shop、商品goods、活动huodong、优惠券coupon、广告ad
 * @param $id 被推荐类型id
 * @param $wid
 * @param $status  0未推荐，1已推荐
 */
function tui($type,$id,$wid,$status,$content ='')
{


    $eq['type'] = $type;
    $eq['aid'] = $id;
    $eq['wid'] = $wid;
    if($content){
        $eq['content'] = $content;
    }
    $list = M('tui')->where($eq)->find();
    $tui = M('tui_cate')->where(['type'=>$type,'wid'=>$wid])->find();
    $data['tid'] = $tui['id'];
    $data['type'] = $type;
    $data['aid'] = $id;
    $data['wid'] = $wid;
    $data['status'] = $status;
    if($content){
        $data['content'] = $content;
    }
    $data['createtime'] = date("Y-m-d H:i:s",time());
    if($list){
        $r = M('tui')->where($eq)->save($data);
    }else{
        $r = M('tui')->add($data);
    }
    if($r){
        return true;
    }else{
        return false;
    }
}

//请求接口获得模板消息
function getTemplate($offset=0,$count=20)
{
    $wid = session('wid');
    //获取微信的access_token
    $fcount = M("form")->where(['wid'=>$wid])->count();
    if($fcount <25){
        $access_token = get_access_token_mp();
        $url = "https://api.weixin.qq.com/cgi-bin/wxopen/template/list?access_token=".$access_token;
        //请求参数
        $dd = array();
        $dd['offset']=$offset;
        $dd['count']=$count;
        $result = ihttp_post($url,json_encode($dd));
        $result = json_decode($result,true);
        if($result['errmsg'] == "ok"){//请求成功存入数据库
            foreach($result['list'] as $v){
                $data['wid']= $wid;
                $data['template_id']=$v['template_id'];
                $data['title'] = $v['title'];
                $data['content']= $v['content'];
                $data['example']=$v['example'];
                $data['createtime'] = date("Y-m-d H:i:s",time());
                $have = M('form')->where(['wid'=>$wid,'template_id'=>$v['template_id']])->find();
                if(!$have){
                    M('form')->add($data);
                }
                unset($have);
                unset($data);
            }
        }
        if($offset <20 && $fcount <20){
            getTemplate(20,20);
        }
    }

}

/*
 * 发送购买成功通知
 * 普通订单支付成功后用户收到模板消息，同时商家也要收到消息
 * @param $openid       opneid
 * @param $out_trade_no  订单号
 * @return bool
 */
function sendOrderMessage($openid,$out_trade_no,$wid)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%购买成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('order')->alias('o')->field("o.*,s.name")->join('tp_shop s on s.shop_id = o.shop_id')->where(['out_trade_no'=>$out_trade_no])->find();
    //组装data

    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$info['name'], //购买地点
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$info['create_time'], //购买时间
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$info['title'],//物品名称
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$out_trade_no,//交易单号
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>"￥".$info['pay_money']."元",//购买价格
            "color"=>"#9b9b9b"
        ),
    );

    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 0 || $result['errcode'] == 41028 || $result['errcode'] == 41029){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 拼团成功模板消息
 * 发送给团长和参团的人以及商家
 */
function sendTuanMessage($openid,$out_trade_no,$wid)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }

    //查出模板id
    $where['title'] = array("like","%提现到账%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //判断是团长还是个人
    $order = M("order")->where(['out_trade_no'=>$out_trade_no])->find();
    if($order['is_tuan'] && $order['is_tuan_first']){
        //团长
        $user = M('user')->where(['openid'=>$order['openid'],'wid'=>$order['wid']])->find();
    }else{
        //团员
        $tuan = M("order")->where(['id'=>$order['tuan_first_id']])->find();
        $user = M('user')->where(['openid'=>$tuan['openid'],'wid'=>$order['wid']])->find();
    }
    if(!$user){
        return false;
    }
    //商品原价
    $goods = M('goods')->where(['id'=>$order['goods_id']])->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$order['title'], //活动名称
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$user['nickname'], //团长
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$order['tuan_need_num'],//成团人数
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>$order['title'],//商品名称
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$goods['price'],//商品金额
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>$tuan?$tuan['create_time']:$order['create_time'],//开团时间
            "color"=>"#9b9b9b"
        ),
        "keyword7"=>array(
            "value"=>$order['price'],//拼团价
            "color"=>"#9b9b9b"
        ),
        "keyword8"=>array(
            "value"=>"如果未按承诺时间发货，系统将按照规则进 行赔偿。",//温馨提示
            "color"=>"#9b9b9b"
        ),
        "keyword9"=>array(
            "value"=>$out_trade_no,//提货码
            "color"=>"#9b9b9b"
        )
    );

    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 0 || $result['errcode'] == 41028 || $result['errcode'] == 41029){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送砍价进度通知
 * 砍价进度通知
 * @param $openid       opneid
 * @param $kanid  砍价日志表id
 * @param $kan_num  已有几人砍价
 * @param $kan_total  已砍价多少钱
 * @param $wid  wid
 * @return bool
 */
function sendKanMessage($openid,$kanid,$kan_num,$kan_total,$wid,$type)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%砍价进度%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('goods')->alias('g')->field("k.*,g.title,g.price,g.stock,g.kan_price")->join('tp_kan_log k on k.goods_id = g.id')->where(['k.id'=>$kanid])->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid

    if($type == "ing"){
        //砍价进度
        $value = array(
            "keyword1"=>array(
                "value"=>$info['title'], //商品名称
                "color"=>"#4a4a4a"
            ),
            "keyword2"=>array(
                "value"=>"已有".$kan_num."人砍价", //砍价进度
                "color"=>"#9b9b9b"
            ),
            "keyword3"=>array(
                "value"=>"20时35分17秒",//剩余时间
                "color"=>"#9b9b9b"
            ),
            "keyword4"=>array(
                "value"=>"留给你的时间不多了，快召集好友吧！",//温馨提示
                "color"=>"#9b9b9b"
            ),
            "keyword5"=>array(
                "value"=>$info['stock'],//商品库存
                "color"=>"#9b9b9b"
            ),
            "keyword6"=>array(
                "value"=>"￥".$info['price']."元",//支付金额
                "color"=>"#9b9b9b"
            ),
            "keyword7"=>array(
                "value"=>"￥".$kan_total."元",//砍价金额
                "color"=>"#9b9b9b"
            ),
            "keyword8"=>array(
                "value"=>"￥".intval($info['price'] - $kan_total)."元",//当前价格
                "color"=>"#9b9b9b"
            ),
            "keyword9"=>array(
                "value"=>date("Y-m-d H:i:s",strtotime("+1 days",time())),//结束时间
                "color"=>"#9b9b9b"
            )
        ) ;
    }else{
        //砍价成功
        //砍价进度
        $value = array(
            "keyword1"=>array(
                "value"=>$info['title'], //商品名称
                "color"=>"#4a4a4a"
            ),
            "keyword2"=>array(
                "value"=>"￥".$kan_total."元", //砍价金额
                "color"=>"#9b9b9b"
            ),
            "keyword3"=>array(
                "value"=>"您可以告知您的好友砍价成功哦!",//温馨提示
                "color"=>"#9b9b9b"
            ),
            "keyword4"=>array(
                "value"=>"￥".intval($info['price'] - $kan_total)."元",//支付金额
                "color"=>"#9b9b9b"
            ),
            "keyword5"=>array(
                "value"=>"￥".$info['price']."元",//砍前价格
                "color"=>"#9b9b9b"
            ),
            "keyword6"=>array(
                "value"=>"￥".$kan_total."元",//砍掉价格
                "color"=>"#9b9b9b"
            ),
            "keyword7"=>array(
                "value"=>"￥".$info['kan_price']."元",//底价
                "color"=>"#9b9b9b"
            ),
            "keyword8"=>array(
                "value"=>$info['last_time'],//砍价时间
                "color"=>"#9b9b9b"
            ),
            "keyword9"=>array(
                "value"=>"活动时间结束",//砍价状态
                "color"=>"#9b9b9b"
            )
        ) ;
    }


    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 0 || $result['errcode'] == 41028 || $result['errcode'] == 41029){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

/*
 * 发送请购成功通知
 * @param $openid       opneid
 * @param $out_trade_no  订单号
 * @return bool
 */
function sendQiangMessage($openid,$out_trade_no,$wid)
{
    if(!$openid){
        return false;
    }
    //获取微信的access_token
    $access_token = get_access_token_mp($wid);
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    //获得formid
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%抢购成功%");
    $where['wid'] = $wid;
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //查出订单详情
    $info = M('order')->alias('o')->field("o.*,s.name")->join('tp_shop s on s.shop_id = o.shop_id')->where(['out_trade_no'=>$out_trade_no])->find();
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid

    $value = array(
        "keyword1" => array(
            "value" => $info['title'], //商品名称
            "color" => "#4a4a4a"
        ),
        "keyword2" => array(
            "value" => $info['name'], //商品价格
            "color" => "#9b9b9b"
        ),
        "keyword3" => array(
            "value" => $info['create_time'],//抢购时间
            "color" => "#9b9b9b"
        ),
        "keyword4" => array(
            "value" => "美食",//产品类型
            "color" => "#9b9b9b"
        ),
        "keyword5" => array(
            "value" => "送货上门",//产品服务
            "color" => "#9b9b9b"
        ),
        "keyword6" => array(
            "value" => $info['name'] ,//商户名称
            "color" => "#9b9b9b"
        ),
        "keyword7" => array(
            "value" => "1" ,//购买数量
            "color" => "#9b9b9b"
        ),
        "keyword8" => array(
            "value" => "￥" . $info['pay_money']  . "元",//总金额
            "color" => "#9b9b9b"
        ),
        "keyword9" => array(
            "value" => date("Y-m-d H:i:s", strtotime("+1 days", time())),//消费截止
            "color" => "#9b9b9b"
        )
    );


    $page = "pages/index/index";//打开页面
    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 0 || $result['errcode'] == 41028 || $result['errcode'] == 41029){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
//提现成功通知！
function sendWithdrawMessage($openid,$withdrawid)
{
    //获取微信的access_token
    $access_token = get_access_token_mp();
    //查出可用的formid
    $map['openid'] = $openid;
    $map[] = ['used_num < max_num'];
    $map['end_time'] =['gt',date("Y-m-d H:i:s",(time()+200))];
    $formid = M('formid')->where($map)->order('end_time asc')->find();
    if(!$formid){
        return false;
    }
    //查出提现内容
    $withdraw = M('withdraw')->where(array('id'=>$withdrawid))->find();
    if(!$withdrawid){
        return false;
    }
    //查出模板id
    $where['title'] = array("like","%提现到账%");
    $where['wid'] = session('wid');
    $form = M('form')->where($where)->find();
    if(!$form){
        return false;
    }
    //组装data
    $touser = $openid;//接受者openid
    $template_id = $form['template_id'];
    $form_id =$formid['form_id'];//formid
    $value = array(
        "keyword1"=>array(
            "value"=>$withdraw['real_money'], //到账金额
            "color"=>"#4a4a4a"
        ),
        "keyword2"=>array(
            "value"=>$withdraw['apply_money'], //提现金额
            "color"=>"#9b9b9b"
        ),
        "keyword3"=>array(
            "value"=>$withdraw['rate']."%",//手续费
            "color"=>"#9b9b9b"
        ),
        "keyword4"=>array(
            "value"=>"微信钱包",//提现至
            "color"=>"#9b9b9b"
        ),
        "keyword5"=>array(
            "value"=>$withdraw['remit_time'],//到账时间
            "color"=>"#9b9b9b"
        ),
        "keyword6"=>array(
            "value"=>$withdraw['createtime'],//提现申请时间
            "color"=>"#9b9b9b"
        ),
        "keyword7"=>array(
            "value"=>"提现已发至您的微信钱包，请查收",//温馨提示
            "color"=>"#9b9b9b"
        )
    );
    if($withdraw['shop_id']){
        //商家提现 之后还有用户提现等，故加判断
        $page = "pages/index/index?shop_id={$withdrawid['shop_id']}&wid={$withdrawid['wid']}";//打开页面
    }


    $url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$access_token;
    $dd = array();
    $dd['touser']=$touser;
    $dd['template_id']=$template_id;
    $dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
    $dd['form_id']=$form_id;
    $dd['data']=$value;                        //模板内容，不填则下发空模板
    $dd['emphasis_keyword']='';    //模板需要放大的关键词，不填则默认无放大
    $result = ihttp_post($url,json_encode($dd));
    $result = json_decode($result,true);
    if($result['errcode'] == 0 || $result['errcode'] == 41028 || $result['errcode'] == 41029){
        //发送成功,formid修改
        $r =  M('formid')->where(array('id'=>$formid['id']))->order('end_time asc')->setInc('used_num');
        if($r){
            return true;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

//获取微信公众平台token
function get_access_token_mp($wid)
{
    $wid = session('wid')?session('wid'):$wid;
    $wechat = M('wechat')->where(array('wid'=>$wid))->find();
    /*$token = S("access_token_mp");
    if($token){
        return $token;
    }*/
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$wechat['appid']}&secret={$wechat['app_secret']}";
    $res = ihttp_get($url);
    $td = json_decode($res, true);
    if($td['access_token']){
        S("access_token_mp", $td['access_token'], $td['expires_in'] - 120);
        return $td['access_token'];
    }else{
        return false;
    }
}

function ihttp_post($url, $post_data){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}

function ihttp_get($url){
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    $out = curl_exec($ch);
    curl_close($ch);
    return $out;
}
